Artificial Intelligence Nanodegree

Project: Dog Breed Identification App using CNNs and Keras


Why We're Here

In this notebook, you will make the first steps towards developing an algorithm that could be used as part of a mobile or web app. At the end of this project, your code will accept any user-supplied image as input. If a dog is detected in the image, it will provide an estimate of the dog's breed. If a human is detected, it will provide an estimate of the dog breed that is most resembling. The image below displays potential sample output of your finished project (... but we expect that each student's algorithm will behave differently!).

Sample Dog Output

In this real-world setting, you will need to piece together a series of models to perform different tasks; for instance, the algorithm that detects humans in an image will be different from the CNN that infers dog breed. There are many points of possible failure, and no perfect algorithm exists. Your imperfect solution will nonetheless create a fun user experience!

The Road Ahead

We break the notebook into separate steps. Feel free to use the links below to navigate the notebook.

  • Step 0: Import Datasets
  • Step 1: Detect Humans
  • Step 2: Detect Dogs
  • Step 3: Create a CNN to Classify Dog Breeds (from Scratch)
  • Step 4: Use a CNN to Classify Dog Breeds (using Transfer Learning)
  • Step 5: Create a CNN to Classify Dog Breeds (using Transfer Learning)
  • Step 6: Write your Algorithm
  • Step 7: Test Your Algorithm

Step 0: Import Datasets

Import Dog Dataset

In the code cell below, we import a dataset of dog images. We populate a few variables through the use of the load_files function from the scikit-learn library:

  • train_files, valid_files, test_files - numpy arrays containing file paths to images
  • train_targets, valid_targets, test_targets - numpy arrays containing onehot-encoded classification labels
  • dog_names - list of string-valued dog breed names for translating labels
In [58]:
from sklearn.datasets import load_files       
from keras.utils import np_utils
import numpy as np
from glob import glob
In [59]:
# define function to load train, test, and validation datasets
def load_dataset(path):
    data = load_files(path)
    dog_files = np.array(data['filenames'])
    dog_targets = np_utils.to_categorical(np.array(data['target']), 133)
    return dog_files, dog_targets

# load train, test, and validation datasets
train_files, train_targets = load_dataset('dogImages/train')
valid_files, valid_targets = load_dataset('dogImages/valid')
test_files, test_targets = load_dataset('dogImages/test')

# load list of dog names
dog_names = [item[20:-1] for item in sorted(glob("dogImages/train/*/"))]

# print statistics about the dataset
print('There are %d total dog categories.' % len(dog_names))
print('There are %s total dog images.\n' % len(np.hstack([train_files, valid_files, test_files])))
print('There are %d training dog images.' % len(train_files))
print('There are %d validation dog images.' % len(valid_files))
print('There are %d test dog images.'% len(test_files))
There are 133 total dog categories.
There are 8351 total dog images.

There are 6680 training dog images.
There are 835 validation dog images.
There are 836 test dog images.

Import Human Dataset

In the code cell below, we import a dataset of human images, where the file paths are stored in the numpy array human_files.

In [60]:
import random
random.seed(8675309)

# load filenames in shuffled human dataset
human_files = np.array(glob("lfw/*/*"))
random.shuffle(human_files)

# print statistics about the dataset
print('There are %d total human images.' % len(human_files))
There are 13233 total human images.

Step 1: Detect Humans

We use OpenCV's implementation of Haar feature-based cascade classifiers to detect human faces in images. OpenCV provides many pre-trained face detectors, stored as XML files on github. We have downloaded one of these detectors and stored it in the haarcascades directory.

In the next code cell, we demonstrate how to use this detector to find human faces in a sample image.

In [61]:
import cv2                
import matplotlib.pyplot as plt                        
%matplotlib inline
In [109]:
# extract pre-trained face detector
face_cascade = cv2.CascadeClassifier('haarcascades/haarcascade_frontalface_alt.xml')

# load color (BGR) image
img = cv2.imread(human_files[19])
# convert BGR image to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# find faces in image
faces = face_cascade.detectMultiScale(gray)

# print number of faces detected in the image
print('Number of faces detected:', len(faces))

# get bounding box for each detected face
for (x,y,w,h) in faces:
    # add bounding box to color image
    cv2.rectangle(img,(x,y),(x+w,y+h),(66,244,92),3)
    
# convert BGR image to RGB for plotting
cv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

# display the image, along with bounding box
plt.imshow(cv_rgb)
plt.axis('off')
plt.show()
Number of faces detected: 1

Before using any of the face detectors, it is standard procedure to convert the images to grayscale. The detectMultiScale function executes the classifier stored in face_cascade and takes the grayscale image as a parameter.

In the above code, faces is a numpy array of detected faces, where each row corresponds to a detected face. Each detected face is a 1D array with four entries that specifies the bounding box of the detected face. The first two entries in the array (extracted in the above code as x and y) specify the horizontal and vertical positions of the top left corner of the bounding box. The last two entries in the array (extracted here as w and h) specify the width and height of the box.

Write a Human Face Detector

We can use this procedure to write a function that returns True if a human face is detected in an image and False otherwise. This function, aptly named face_detector, takes a string-valued file path to an image as input and appears in the code block below.

In [110]:
# returns "True" if face is detected in image stored at img_path
def face_detector(img_path):
    img = cv2.imread(img_path)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray)
    return len(faces) > 0

Assess the Human Face Detector

Question 1: Use the code cell below to test the performance of the face_detector function.

  • What percentage of the first 100 images in human_files have a detected human face?
  • What percentage of the first 100 images in dog_files have a detected human face?

Ideally, we would like 100% of human images with a detected face and 0% of dog images with a detected face. You will see that our algorithm falls short of this goal, but still gives acceptable performance. We extract the file paths for the first 100 images from each of the datasets and store them in the numpy arrays human_files_short and dog_files_short.

Answer:

In [64]:
human_files_short = human_files[:100]
dog_files_short = train_files[:100]
# Do NOT modify the code above this line.

## TODO: Test the performance of the face_detector algorithm 
## on the images in human_files_short and dog_files_short.

human_detections = np.sum([face_detector(img) for img in human_files_short])
dog_detections = np.sum([face_detector(img) for img in dog_files_short])

print('face detection in human image set = {}%'.format(human_detections))
print('face detection in dog image set = {}%'.format(dog_detections))
face detection in human image set = 99%
face detection in dog image set = 11%

Question 2: This algorithmic choice necessitates that we communicate to the user that we accept human images only when they provide a clear view of a face (otherwise, we risk having unneccessarily frustrated users!). In your opinion, is this a reasonable expectation to pose on the user? If not, can you think of a way to detect humans in images that does not necessitate an image with a clearly presented face?

Answer: Perhaps this is reasonable given the limitations of the training data. If the model has only been trained on images with clearly visible faces, then we can't expect it to identify faces in other types of images where faces aren't clearly visible. However, we should try to deliver a more versatile product for our users.

One simple way to make the model more versatile would be via data augmentation. Essentially, we would apply various transformations to the training images such as cropping, shearing, warping, axis rotations, and occlusions. This way, the model could learn to identify faces even when they're not clearly visible. The nice thing about this approach is that we can use the same training data and simply retrain the model already in use.

However, if the ultimate goal is to detect humans in images even if a face isn't present, then a more robust approach would be to gather additional training images which include other parts of the human body. This way we could train the model to identify humans by other characteristics than just their face.


Step 2: Detect Dogs

In this section, we use a pre-trained ResNet-50 model to detect dogs in images. Our first line of code downloads the ResNet-50 model, along with weights that have been trained on ImageNet, a very large, very popular dataset used for image classification and other vision tasks. ImageNet contains over 10 million URLs, each linking to an image containing an object from one of 1000 categories. Given an image, this pre-trained ResNet-50 model returns a prediction (derived from the available categories in ImageNet) for the object that is contained in the image.

In [65]:
from keras.applications.resnet50 import ResNet50

# define ResNet50 model
ResNet50_model = ResNet50(weights='imagenet')

Pre-process the Data

When using TensorFlow as backend, Keras CNNs require a 4D array (which we'll also refer to as a 4D tensor) as input, with shape

$$ (\text{nb_samples}, \text{rows}, \text{columns}, \text{channels}), $$

where nb_samples corresponds to the total number of images (or samples), and rows, columns, and channels correspond to the number of rows, columns, and channels for each image, respectively.

The path_to_tensor function below takes a string-valued file path to a color image as input and returns a 4D tensor suitable for supplying to a Keras CNN. The function first loads the image and resizes it to a square image that is $224 \times 224$ pixels. Next, the image is converted to an array, which is then resized to a 4D tensor. In this case, since we are working with color images, each image has three channels. Likewise, since we are processing a single image (or sample), the returned tensor will always have shape

$$ (1, 224, 224, 3). $$

The paths_to_tensor function takes a numpy array of string-valued image paths as input and returns a 4D tensor with shape

$$ (\text{nb_samples}, 224, 224, 3). $$

Here, nb_samples is the number of samples, or number of images, in the supplied array of image paths. It is best to think of nb_samples as the number of 3D tensors (where each 3D tensor corresponds to a different image) in your dataset!

In [111]:
from keras.preprocessing import image                  
from tqdm import tqdm

def path_to_tensor(img_path):
    # loads RGB image as PIL.Image.Image type
    img = image.load_img(img_path, target_size=(224, 224))
    # convert PIL.Image.Image type to 3D tensor with shape (224, 224, 3)
    x = image.img_to_array(img)
    # convert 3D tensor to 4D tensor with shape (1, 224, 224, 3) and return 4D tensor
    return np.expand_dims(x, axis=0)

def paths_to_tensor(img_paths):
    list_of_tensors = [path_to_tensor(img_path) for img_path in tqdm(img_paths)]
    return np.vstack(list_of_tensors)

Making Predictions with ResNet-50

Getting the 4D tensor ready for ResNet-50, and for any other pre-trained model in Keras, requires some additional processing. First, the RGB image is converted to BGR by reordering the channels. All pre-trained models have the additional normalization step that the mean pixel (expressed in RGB as $[103.939, 116.779, 123.68]$ and calculated from all pixels in all images in ImageNet) must be subtracted from every pixel in each image. This is implemented in the imported function preprocess_input. If you're curious, you can check the code for preprocess_input here.

Now that we have a way to format our image for supplying to ResNet-50, we are now ready to use the model to extract the predictions. This is accomplished with the predict method, which returns an array whose $i$-th entry is the model's predicted probability that the image belongs to the $i$-th ImageNet category. This is implemented in the ResNet50_predict_labels function below.

By taking the argmax of the predicted probability vector, we obtain an integer corresponding to the model's predicted object class, which we can identify with an object category through the use of this dictionary.

In [112]:
from keras.applications.resnet50 import preprocess_input, decode_predictions

def ResNet50_predict_labels(img_path):
    # returns prediction vector for image located at img_path
    img = preprocess_input(path_to_tensor(img_path))
    return np.argmax(ResNet50_model.predict(img))

Write a Dog Detector

While looking at the dictionary, you will notice that the categories corresponding to dogs appear in an uninterrupted sequence and correspond to dictionary keys 151-268, inclusive, to include all categories from 'Chihuahua' to 'Mexican hairless'. Thus, in order to check to see if an image is predicted to contain a dog by the pre-trained ResNet-50 model, we need only check if the ResNet50_predict_labels function above returns a value between 151 and 268 (inclusive).

We use these ideas to complete the dog_detector function below, which returns True if a dog is detected in an image (and False if not).

In [113]:
### returns "True" if a dog is detected in the image stored at img_path
def dog_detector(img_path):
    prediction = ResNet50_predict_labels(img_path)
    return ((prediction <= 268) & (prediction >= 151)) 

Assess the Dog Detector

Question 3: Use the code cell below to test the performance of your dog_detector function.

  • What percentage of the images in human_files_short have a detected dog?
  • What percentage of the images in dog_files_short have a detected dog?

Answer:

In [69]:
### TODO: Test the performance of the dog_detector function
### on the images in human_files_short and dog_files_short.
human_as_dog_pct = sum([dog_detector(image) for image in human_files_short])
dog_as_dog_pct = sum([dog_detector(image) for image in dog_files_short])

print("Images with humans incorrectly detected as dogs: {}%".format(human_as_dog_pct))
print("Images with dogs correctly detected as dogs: {}%".format(dog_as_dog_pct))
Images with humans incorrectly detected as dogs: 0%
Images with dogs correctly detected as dogs: 100%

Step 3: Create a CNN to Classify Dog Breeds (from Scratch)

Now that we have functions for detecting humans and dogs in images, we need a way to predict breed from images. In this step, you will create a CNN that classifies dog breeds. You must create your CNN from scratch (so, you can't use transfer learning yet!), and you must attain a test accuracy of at least 1%. In Step 5 of this notebook, you will have the opportunity to use transfer learning to create a CNN that attains greatly improved accuracy.

Be careful with adding too many trainable layers! More parameters means longer training, which means you are more likely to need a GPU to accelerate the training process. Thankfully, Keras provides a handy estimate of the time that each epoch is likely to take; you can extrapolate this estimate to figure out how long it will take for your algorithm to train.

We mention that the task of assigning breed to dogs from images is considered exceptionally challenging. To see why, consider that even a human would have great difficulty in distinguishing between a Brittany and a Welsh Springer Spaniel.

Brittany Welsh Springer Spaniel

It is not difficult to find other dog breed pairs with minimal inter-class variation (for instance, Curly-Coated Retrievers and American Water Spaniels).

Curly-Coated Retriever American Water Spaniel

Likewise, recall that labradors come in yellow, chocolate, and black. Your vision-based algorithm will have to conquer this high intra-class variation to determine how to classify all of these different shades as the same breed.

Yellow Labrador Chocolate Labrador Black Labrador

We also mention that random chance presents an exceptionally low bar: setting aside the fact that the classes are slightly imabalanced, a random guess will provide a correct answer roughly 1 in 133 times, which corresponds to an accuracy of less than 1%.

Remember that the practice is far ahead of the theory in deep learning. Experiment with many different architectures, and trust your intuition. And, of course, have fun!

Pre-process the Data

We rescale the images by dividing every pixel in every image by 255.

In [70]:
from PIL import ImageFile                            
ImageFile.LOAD_TRUNCATED_IMAGES = True                 

# pre-process the data for Keras
train_tensors = paths_to_tensor(train_files).astype('float32')/255
valid_tensors = paths_to_tensor(valid_files).astype('float32')/255
test_tensors = paths_to_tensor(test_files).astype('float32')/255
100%|██████████| 6680/6680 [01:51<00:00, 59.78it/s]
100%|██████████| 835/835 [00:12<00:00, 66.65it/s]
100%|██████████| 836/836 [00:12<00:00, 67.14it/s]

Model Architecture

Create a CNN to classify dog breed. At the end of your code cell block, summarize the layers of your model by executing the line:

    model.summary()

We have imported some Python modules to get you started, but feel free to import as many modules as you need. If you end up getting stuck, here's a hint that specifies a model that trains relatively fast on CPU and attains >1% test accuracy in 5 epochs:

Sample CNN

Question 4: Outline the steps you took to get to your final CNN architecture and your reasoning at each step. If you chose to use the hinted architecture above, describe why you think that CNN architecture should work well for the image classification task.

Answer:

My chosen architecture can be found below. It was inspired by this model created by the Keras team for a similar classification task on the CIFAR data set. My chosen architecture happens to be similar to the sample architecture provided above. Both have three convolutional layers with 16/32/64 filters respectively, each followed by a max pooling layer.

However, my chosen model includes an additional connected layer ("Dense" layer) with 512 nodes. This should boost the model's ability to map distinct spatial patterns from the convolutional layers to their corresponding dog breed. But, this additional modeling power comes at a price. My model has over 25 million parameters (more than a 1000x increase), compared to less than 20k for the sample model. The bigger model is also more prone to overfitting, so I've added two dropout layers and L2 regularization to help combat this.

Summary of Steps Taken:

  1. Trained and tested sample model above. Accuracy was 2.9%, which is better than random, but still not great.
  2. Explored other Keras architectures used for classification tasks.
  3. Selected CIFAR archictecture as template due to simplicity of model and relative similarity of CIFAR data set to our dog breed data set.
  4. Implemented, trained, tested the CIFAR model.
  5. Accuracy improved to 5%, but it was overfitting with very few epochs (i.e. high accuracy on training data but low accuracy on validation set)
  6. Tried different values for dropout rate to reduce overfitting.
  7. Model was still overfitting, so I added L2 regularization. Final test accuracy reached 8.6%.
In [71]:
from keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D
from keras.layers import Dropout, Flatten, Dense
from keras.models import Sequential
from keras.regularizers import l2
In [72]:
model = Sequential()

### TODO: Define your architecture.
drop1 = 0.25     # initial dropout rate
drop2 = 0.5      # secondary dropout rate
d_act = 'relu'   # default activation function
d_pad = 'same'   # default padding
reg = l2(1e-3)   # L2 reg

model = Sequential()
model.add(Conv2D(16, 2, input_shape=train_tensors.shape[1:], padding=d_pad, activation=d_act, kernel_regularizer=reg, name='block1_conv1'))
model.add(MaxPooling2D(pool_size=2))
model.add(Conv2D(32, 2, padding=d_pad, activation=d_act, kernel_regularizer=reg, name='block2_conv1'))
model.add(MaxPooling2D(pool_size=2))
model.add(Conv2D(64, 2, padding=d_pad, activation=d_act, kernel_regularizer=reg, name='block3_conv1'))
model.add(MaxPooling2D(pool_size=2))
model.add(Dropout(drop1))
model.add(Flatten())
model.add(Dense(512, activation=d_act, kernel_regularizer=reg))
model.add(Dropout(drop2))
model.add(Dense(len(dog_names), activation='softmax'))

model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
block1_conv1 (Conv2D)        (None, 224, 224, 16)      208       
_________________________________________________________________
max_pooling2d_3 (MaxPooling2 (None, 112, 112, 16)      0         
_________________________________________________________________
block2_conv1 (Conv2D)        (None, 112, 112, 32)      2080      
_________________________________________________________________
max_pooling2d_4 (MaxPooling2 (None, 56, 56, 32)        0         
_________________________________________________________________
block3_conv1 (Conv2D)        (None, 56, 56, 64)        8256      
_________________________________________________________________
max_pooling2d_5 (MaxPooling2 (None, 28, 28, 64)        0         
_________________________________________________________________
dropout_2 (Dropout)          (None, 28, 28, 64)        0         
_________________________________________________________________
flatten_3 (Flatten)          (None, 50176)             0         
_________________________________________________________________
dense_4 (Dense)              (None, 512)               25690624  
_________________________________________________________________
dropout_3 (Dropout)          (None, 512)               0         
_________________________________________________________________
dense_5 (Dense)              (None, 133)               68229     
=================================================================
Total params: 25,769,397
Trainable params: 25,769,397
Non-trainable params: 0
_________________________________________________________________

Compile the Model

In [73]:
model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])

Train the Model

Train your model in the code cell below. Use model checkpointing to save the model that attains the best validation loss.

You are welcome to augment the training data, but this is not a requirement.

In [74]:
from keras.callbacks import Callback, EarlyStopping, ModelCheckpoint
In [75]:
### TODO: specify the number of epochs that you would like to use to train the model.

epochs = 10

### Do NOT modify the code below this line.

checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.from_scratch.hdf5', 
                               verbose=1, save_best_only=True)

model.fit(train_tensors, train_targets, 
          validation_data=(valid_tensors, valid_targets),
          epochs=epochs, batch_size=20, callbacks=[checkpointer], verbose=1)
Train on 6680 samples, validate on 835 samples
Epoch 1/10
6680/6680 [==============================] - 28s 4ms/step - loss: 5.0282 - acc: 0.0102 - val_loss: 4.8792 - val_acc: 0.0204

Epoch 00001: val_loss improved from inf to 4.87923, saving model to saved_models/weights.best.from_scratch.hdf5
Epoch 2/10
6680/6680 [==============================] - 24s 4ms/step - loss: 4.8151 - acc: 0.0229 - val_loss: 4.7220 - val_acc: 0.0263

Epoch 00002: val_loss improved from 4.87923 to 4.72201, saving model to saved_models/weights.best.from_scratch.hdf5
Epoch 3/10
6680/6680 [==============================] - 24s 4ms/step - loss: 4.6550 - acc: 0.0340 - val_loss: 4.5531 - val_acc: 0.0419

Epoch 00003: val_loss improved from 4.72201 to 4.55314, saving model to saved_models/weights.best.from_scratch.hdf5
Epoch 4/10
6680/6680 [==============================] - 24s 4ms/step - loss: 4.5116 - acc: 0.0461 - val_loss: 4.4999 - val_acc: 0.0575

Epoch 00004: val_loss improved from 4.55314 to 4.49988, saving model to saved_models/weights.best.from_scratch.hdf5
Epoch 5/10
6680/6680 [==============================] - 24s 4ms/step - loss: 4.4202 - acc: 0.0522 - val_loss: 4.3876 - val_acc: 0.0611

Epoch 00005: val_loss improved from 4.49988 to 4.38765, saving model to saved_models/weights.best.from_scratch.hdf5
Epoch 6/10
6680/6680 [==============================] - 24s 4ms/step - loss: 4.3530 - acc: 0.0638 - val_loss: 4.3791 - val_acc: 0.0695

Epoch 00006: val_loss improved from 4.38765 to 4.37906, saving model to saved_models/weights.best.from_scratch.hdf5
Epoch 7/10
6680/6680 [==============================] - 24s 4ms/step - loss: 4.3014 - acc: 0.0680 - val_loss: 4.3545 - val_acc: 0.0707

Epoch 00007: val_loss improved from 4.37906 to 4.35447, saving model to saved_models/weights.best.from_scratch.hdf5
Epoch 8/10
6680/6680 [==============================] - 24s 4ms/step - loss: 4.2411 - acc: 0.0762 - val_loss: 4.3370 - val_acc: 0.0910

Epoch 00008: val_loss improved from 4.35447 to 4.33701, saving model to saved_models/weights.best.from_scratch.hdf5
Epoch 9/10
6680/6680 [==============================] - 24s 4ms/step - loss: 4.1986 - acc: 0.0897 - val_loss: 4.3318 - val_acc: 0.0587

Epoch 00009: val_loss improved from 4.33701 to 4.33178, saving model to saved_models/weights.best.from_scratch.hdf5
Epoch 10/10
6680/6680 [==============================] - 24s 4ms/step - loss: 4.1472 - acc: 0.0987 - val_loss: 4.3135 - val_acc: 0.0886

Epoch 00010: val_loss improved from 4.33178 to 4.31348, saving model to saved_models/weights.best.from_scratch.hdf5
Out[75]:
<keras.callbacks.History at 0x7f2609f8a7b8>

Load the Model with the Best Validation Loss

In [76]:
model.load_weights('saved_models/weights.best.from_scratch.hdf5')

Test the Model

Try out your model on the test dataset of dog images. Ensure that your test accuracy is greater than 1%.

In [77]:
# get index of predicted dog breed for each image in test set
dog_breed_predictions = [np.argmax(model.predict(np.expand_dims(tensor, axis=0))) for tensor in test_tensors]

# report test accuracy
test_accuracy = 100*np.sum(np.array(dog_breed_predictions)==np.argmax(test_targets, axis=1))/len(dog_breed_predictions)
print('Test accuracy: %.4f%%' % test_accuracy)
Test accuracy: 8.6124%

Step 4: Use a CNN to Classify Dog Breeds

To reduce training time without sacrificing accuracy, we show you how to train a CNN using transfer learning. In the following step, you will get a chance to use transfer learning to train your own CNN.

Obtain Bottleneck Features

In [78]:
bottleneck_features = np.load('bottleneck_features/DogVGG16Data.npz')
train_VGG16 = bottleneck_features['train']
valid_VGG16 = bottleneck_features['valid']
test_VGG16 = bottleneck_features['test']

Model Architecture

The model uses the the pre-trained VGG-16 model as a fixed feature extractor, where the last convolutional output of VGG-16 is fed as input to our model. We only add a global average pooling layer and a fully connected layer, where the latter contains one node for each dog category and is equipped with a softmax.

In [79]:
VGG16_model = Sequential()
VGG16_model.add(GlobalAveragePooling2D(input_shape=train_VGG16.shape[1:]))
VGG16_model.add(Dense(133, activation='softmax'))

VGG16_model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
global_average_pooling2d_3 ( (None, 512)               0         
_________________________________________________________________
dense_6 (Dense)              (None, 133)               68229     
=================================================================
Total params: 68,229
Trainable params: 68,229
Non-trainable params: 0
_________________________________________________________________

Compile the Model

In [80]:
VGG16_model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])

Train the Model

In [81]:
checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.VGG16.hdf5', 
                               verbose=1, save_best_only=True)

VGG16_model.fit(train_VGG16, train_targets, 
          validation_data=(valid_VGG16, valid_targets),
          epochs=20, batch_size=20, callbacks=[checkpointer], verbose=1)
Train on 6680 samples, validate on 835 samples
Epoch 1/20
6680/6680 [==============================] - 4s 607us/step - loss: 12.4274 - acc: 0.1225 - val_loss: 10.8207 - val_acc: 0.2180

Epoch 00001: val_loss improved from inf to 10.82069, saving model to saved_models/weights.best.VGG16.hdf5
Epoch 2/20
6680/6680 [==============================] - 2s 231us/step - loss: 10.3645 - acc: 0.2645 - val_loss: 10.1152 - val_acc: 0.2802

Epoch 00002: val_loss improved from 10.82069 to 10.11523, saving model to saved_models/weights.best.VGG16.hdf5
Epoch 3/20
6680/6680 [==============================] - 2s 230us/step - loss: 9.8042 - acc: 0.3243 - val_loss: 9.6569 - val_acc: 0.3222

Epoch 00003: val_loss improved from 10.11523 to 9.65685, saving model to saved_models/weights.best.VGG16.hdf5
Epoch 4/20
6680/6680 [==============================] - 2s 228us/step - loss: 9.3478 - acc: 0.3696 - val_loss: 9.3342 - val_acc: 0.3521

Epoch 00004: val_loss improved from 9.65685 to 9.33417, saving model to saved_models/weights.best.VGG16.hdf5
Epoch 5/20
6680/6680 [==============================] - 2s 229us/step - loss: 9.0012 - acc: 0.3969 - val_loss: 9.1054 - val_acc: 0.3725

Epoch 00005: val_loss improved from 9.33417 to 9.10536, saving model to saved_models/weights.best.VGG16.hdf5
Epoch 6/20
6680/6680 [==============================] - 2s 230us/step - loss: 8.7561 - acc: 0.4210 - val_loss: 9.0279 - val_acc: 0.3641

Epoch 00006: val_loss improved from 9.10536 to 9.02789, saving model to saved_models/weights.best.VGG16.hdf5
Epoch 7/20
6680/6680 [==============================] - 2s 230us/step - loss: 8.6669 - acc: 0.4368 - val_loss: 8.9342 - val_acc: 0.3784

Epoch 00007: val_loss improved from 9.02789 to 8.93421, saving model to saved_models/weights.best.VGG16.hdf5
Epoch 8/20
6680/6680 [==============================] - 2s 229us/step - loss: 8.5150 - acc: 0.4457 - val_loss: 8.6913 - val_acc: 0.3928

Epoch 00008: val_loss improved from 8.93421 to 8.69128, saving model to saved_models/weights.best.VGG16.hdf5
Epoch 9/20
6680/6680 [==============================] - 2s 231us/step - loss: 8.3745 - acc: 0.4617 - val_loss: 8.7113 - val_acc: 0.3940

Epoch 00009: val_loss did not improve from 8.69128
Epoch 10/20
6680/6680 [==============================] - 2s 229us/step - loss: 8.2375 - acc: 0.4671 - val_loss: 8.5504 - val_acc: 0.3916

Epoch 00010: val_loss improved from 8.69128 to 8.55037, saving model to saved_models/weights.best.VGG16.hdf5
Epoch 11/20
6680/6680 [==============================] - 2s 232us/step - loss: 8.0498 - acc: 0.4787 - val_loss: 8.3330 - val_acc: 0.4036

Epoch 00011: val_loss improved from 8.55037 to 8.33302, saving model to saved_models/weights.best.VGG16.hdf5
Epoch 12/20
6680/6680 [==============================] - 2s 228us/step - loss: 7.7851 - acc: 0.4888 - val_loss: 8.1010 - val_acc: 0.4192

Epoch 00012: val_loss improved from 8.33302 to 8.10104, saving model to saved_models/weights.best.VGG16.hdf5
Epoch 13/20
6680/6680 [==============================] - 2s 229us/step - loss: 7.4461 - acc: 0.5141 - val_loss: 7.9669 - val_acc: 0.4287

Epoch 00013: val_loss improved from 8.10104 to 7.96693, saving model to saved_models/weights.best.VGG16.hdf5
Epoch 14/20
6680/6680 [==============================] - 2s 229us/step - loss: 7.2876 - acc: 0.5272 - val_loss: 7.8141 - val_acc: 0.4311

Epoch 00014: val_loss improved from 7.96693 to 7.81409, saving model to saved_models/weights.best.VGG16.hdf5
Epoch 15/20
6680/6680 [==============================] - 2s 229us/step - loss: 7.1967 - acc: 0.5347 - val_loss: 7.7005 - val_acc: 0.4371

Epoch 00015: val_loss improved from 7.81409 to 7.70054, saving model to saved_models/weights.best.VGG16.hdf5
Epoch 16/20
6680/6680 [==============================] - 2s 228us/step - loss: 7.1391 - acc: 0.5416 - val_loss: 7.7486 - val_acc: 0.4455

Epoch 00016: val_loss did not improve from 7.70054
Epoch 17/20
6680/6680 [==============================] - 2s 229us/step - loss: 6.9831 - acc: 0.5461 - val_loss: 7.4751 - val_acc: 0.4563

Epoch 00017: val_loss improved from 7.70054 to 7.47512, saving model to saved_models/weights.best.VGG16.hdf5
Epoch 18/20
6680/6680 [==============================] - 2s 230us/step - loss: 6.7324 - acc: 0.5638 - val_loss: 7.4964 - val_acc: 0.4467

Epoch 00018: val_loss did not improve from 7.47512
Epoch 19/20
6680/6680 [==============================] - 2s 229us/step - loss: 6.5803 - acc: 0.5740 - val_loss: 7.3167 - val_acc: 0.4659

Epoch 00019: val_loss improved from 7.47512 to 7.31667, saving model to saved_models/weights.best.VGG16.hdf5
Epoch 20/20
6680/6680 [==============================] - 2s 229us/step - loss: 6.5259 - acc: 0.5831 - val_loss: 7.2704 - val_acc: 0.4671

Epoch 00020: val_loss improved from 7.31667 to 7.27040, saving model to saved_models/weights.best.VGG16.hdf5
Out[81]:
<keras.callbacks.History at 0x7f2791a72828>

Load the Model with the Best Validation Loss

In [82]:
VGG16_model.load_weights('saved_models/weights.best.VGG16.hdf5')

Test the Model

Now, we can use the CNN to test how well it identifies breed within our test dataset of dog images. We print the test accuracy below.

In [83]:
# get index of predicted dog breed for each image in test set
VGG16_predictions = [np.argmax(VGG16_model.predict(np.expand_dims(feature, axis=0))) for feature in test_VGG16]

# report test accuracy
test_accuracy = 100*np.sum(np.array(VGG16_predictions)==np.argmax(test_targets, axis=1))/len(VGG16_predictions)
print('Test accuracy: %.4f%%' % test_accuracy)
Test accuracy: 47.8469%

Predict Dog Breed with the Model

In [84]:
from extract_bottleneck_features import *

def VGG16_predict_breed(img_path):
    # extract bottleneck features
    bottleneck_feature = extract_VGG16(path_to_tensor(img_path))
    # obtain predicted vector
    predicted_vector = VGG16_model.predict(bottleneck_feature)
    # return dog breed that is predicted by the model
    return dog_names[np.argmax(predicted_vector)]
In [85]:
VGG16_predict_breed('images/American_water_spaniel_00648.jpg')
Out[85]:
'Flat-coated_retriever'

Incorrect prediction! Let's see if we can do better.


Step 5: Create a CNN to Classify Dog Breeds (using Transfer Learning)

You will now use transfer learning to create a CNN that can identify dog breed from images. Your CNN must attain at least 60% accuracy on the test set.

In Step 4, we used transfer learning to create a CNN using VGG-16 bottleneck features. In this section, you must use the bottleneck features from a different pre-trained model. To make things easier for you, we have pre-computed the features for all of the networks that are currently available in Keras:

The files are encoded as such:

Dog{network}Data.npz

where {network}, in the above filename, can be one of VGG19, Resnet50, InceptionV3, or Xception. Pick one of the above architectures, download the corresponding bottleneck features, and store the downloaded file in the bottleneck_features/ folder in the repository.

Obtain Bottleneck Features

In the code block below, extract the bottleneck features corresponding to the train, test, and validation sets by running the following:

bottleneck_features = np.load('bottleneck_features/Dog{network}Data.npz')
train_{network} = bottleneck_features['train']
valid_{network} = bottleneck_features['valid']
test_{network} = bottleneck_features['test']
In [86]:
### TODO: Obtain bottleneck features from another pre-trained CNN.

bottleneck_features = np.load('bottleneck_features/DogXceptionData.npz')
train_Xception = bottleneck_features['train']
valid_Xception = bottleneck_features['valid']
test_Xception = bottleneck_features['test']

Model Architecture

Create a CNN to classify dog breed. At the end of your code cell block, summarize the layers of your model by executing the line:

    <your model's name>.summary()

Question 5: Outline the steps you took to get to your final CNN architecture and your reasoning at each step. Describe why you think the architecture is suitable for the current problem.

Answer:

First, I tried to get a better sense for the different architectures from this blog post. The Xception architecture sounded most interesting to me. I had some previous experience building an InceptionV3 model on a different Udacity project, so I wanted to try something new. I learned that Xception was inspired by InceptionV3; the name Xception actually stands for “Extreme Inception.” And, Xception has shown better performance than InceptionV3 while also being more efficient, especially on larger data sets.

To get a better understanding of Xception, I read this research article, Xception: Deep Learning with Depthwise Separable Convolutions by François Chollet. Chollet's code for the Keras version of this model can be found here.

According to Chollet, Xception is a convolutional neural network architecture based entirely on depthwise separable convolution layers. He proposes that the mapping of cross-channel and spatial correlations in the feature maps of CNNs can be entirely decoupled, in turn helping the model generalize better.

To implement the model, I took the Xception bottleneck training features as input then added a global average pooling layer and fully connected layers as the paper suggested. I decided to reuse the same fully connected layer structure (with dropout) as I did previously in my CIFAR model. This yielded a test accuracty of 82%.

In [87]:
Xception_model = Sequential()
Xception_model.add(GlobalAveragePooling2D(input_shape=train_Xception.shape[1:]))
Xception_model.add(Dense(512, activation='relu'))
Xception_model.add(Dropout(0.5))
Xception_model.add(Dense(len(dog_names), activation='softmax'))

Xception_model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
global_average_pooling2d_4 ( (None, 2048)              0         
_________________________________________________________________
dense_7 (Dense)              (None, 512)               1049088   
_________________________________________________________________
dropout_4 (Dropout)          (None, 512)               0         
_________________________________________________________________
dense_8 (Dense)              (None, 133)               68229     
=================================================================
Total params: 1,117,317
Trainable params: 1,117,317
Non-trainable params: 0
_________________________________________________________________

Compile the Model

In [88]:
### TODO: Compile the model.

Xception_model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])

Train the Model

Train your model in the code cell below. Use model checkpointing to save the model that attains the best validation loss.

You are welcome to augment the training data, but this is not a requirement.

In [89]:
### TODO: Train the model.

checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.Xception.hdf5', 
                               verbose=1, save_best_only=True)

early_stop = EarlyStopping(monitor='val_loss', min_delta=0.005, patience=5, verbose=0, mode='auto')

Xception_model.fit(train_Xception, train_targets, validation_data=(valid_Xception, valid_targets),
          epochs=20, batch_size=20, callbacks=[checkpointer, early_stop], verbose=1)

print('\nDone Training')
Train on 6680 samples, validate on 835 samples
Epoch 1/20
6680/6680 [==============================] - 6s 828us/step - loss: 1.5807 - acc: 0.6136 - val_loss: 0.6968 - val_acc: 0.7772

Epoch 00001: val_loss improved from inf to 0.69682, saving model to saved_models/weights.best.Xception.hdf5
Epoch 2/20
6680/6680 [==============================] - 3s 430us/step - loss: 0.7268 - acc: 0.7904 - val_loss: 0.5550 - val_acc: 0.8263

Epoch 00002: val_loss improved from 0.69682 to 0.55502, saving model to saved_models/weights.best.Xception.hdf5
Epoch 3/20
6680/6680 [==============================] - 3s 430us/step - loss: 0.6221 - acc: 0.8181 - val_loss: 0.5754 - val_acc: 0.8251

Epoch 00003: val_loss did not improve from 0.55502
Epoch 4/20
6680/6680 [==============================] - 3s 427us/step - loss: 0.5285 - acc: 0.8407 - val_loss: 0.5925 - val_acc: 0.8371

Epoch 00004: val_loss did not improve from 0.55502
Epoch 5/20
6680/6680 [==============================] - 3s 435us/step - loss: 0.4659 - acc: 0.8620 - val_loss: 0.5971 - val_acc: 0.8287

Epoch 00005: val_loss did not improve from 0.55502
Epoch 6/20
6680/6680 [==============================] - 3s 426us/step - loss: 0.4247 - acc: 0.8723 - val_loss: 0.6210 - val_acc: 0.8419

Epoch 00006: val_loss did not improve from 0.55502
Epoch 7/20
6680/6680 [==============================] - 3s 433us/step - loss: 0.3887 - acc: 0.8867 - val_loss: 0.6708 - val_acc: 0.8467

Epoch 00007: val_loss did not improve from 0.55502

Done Training

Load the Model with the Best Validation Loss

In [90]:
### TODO: Load the model weights with the best validation loss.

Xception_model.load_weights('saved_models/weights.best.Xception.hdf5')

Test the Model

Try out your model on the test dataset of dog images. Ensure that your test accuracy is greater than 60%.

In [91]:
### TODO: Calculate classification accuracy on the test dataset.

# get index of predicted dog breed for each image in test set
Xception_predictions = [np.argmax(Xception_model.predict(np.expand_dims(feature, axis=0))) for feature in test_Xception]

# report test accuracy
test_accuracy = 100*np.sum(np.array(Xception_predictions)==np.argmax(test_targets, axis=1))/len(Xception_predictions)
print('Test accuracy: %.2f%%' % test_accuracy)
Test accuracy: 82.06%

Predict Dog Breed with the Model

Write a function that takes an image path as input and returns the dog breed (Affenpinscher, Afghan_hound, etc) that is predicted by your model.

Similar to the analogous function in Step 5, your function should have three steps:

  1. Extract the bottleneck features corresponding to the chosen CNN model.
  2. Supply the bottleneck features as input to the model to return the predicted vector. Note that the argmax of this prediction vector gives the index of the predicted dog breed.
  3. Use the dog_names array defined in Step 0 of this notebook to return the corresponding breed.

The functions to extract the bottleneck features can be found in extract_bottleneck_features.py, and they have been imported in an earlier code cell. To obtain the bottleneck features corresponding to your chosen CNN architecture, you need to use the function

extract_{network}

where {network}, in the above filename, should be one of VGG19, Resnet50, InceptionV3, or Xception.

In [92]:
### TODO: Write a function that takes a path to an image as input
### and returns the dog breed that is predicted by the model.

from extract_bottleneck_features import *


def Xception_predict_breed(img_path, model):
    # extract bottleneck features
    bottleneck_feature = extract_Xception(path_to_tensor(img_path))
    
    # obtain predicted vector
    predicted_vector = model.predict(bottleneck_feature)[0]

    # top 3 dog breeds predicted by the model with probability for each
    indices = predicted_vector.argsort()[-3:][::-1]
    breeds = [dog_names[i] for i in indices]
    confidence = [predicted_vector[i] for i in indices]
    
    return indices, breeds, confidence

Test the predict breed function

In [93]:
indices, breeds, confidence = Xception_predict_breed('images/American_water_spaniel_00648.jpg', Xception_model)
In [94]:
print(indices)
print(breeds)
print(confidence)
[ 8 87 54]
['American_water_spaniel', 'Irish_water_spaniel', 'Curly-coated_retriever']
[0.52128476, 0.35600984, 0.08005773]

Correct! Our new model can now differentiate between American Water Spaniels and Curly Coated Retrievers. The VGG16 model could not do this, so this is progress.


Step 6: Write your Algorithm

Write an algorithm that accepts a file path to an image and first determines whether the image contains a human, dog, or neither. Then,

  • if a dog is detected in the image, return the predicted breed.
  • if a human is detected in the image, return the resembling dog breed.
  • if neither is detected in the image, provide output that indicates an error.

You are welcome to write your own functions for detecting humans and dogs in images, but feel free to use the face_detector and dog_detector functions developed above. You are required to use your CNN from Step 5 to predict dog breed.

Some sample output for our algorithm is provided below, but feel free to design your own user experience!

Sample Human Output

In [97]:
# Create list of image paths to feed into classification algorithm

import cv2
import os, os.path


def create_img_paths(img_dir):
    '''Generates a list of paths for all images within a given directory.'''

    # image directory and valid extensions 
    image_path_list = []
    valid_image_extensions = [".jpg", ".jpeg", ".png", ".tif", ".tiff"] 
    valid_image_extensions = [item.lower() for item in valid_image_extensions]

    # create a list of all files in directory and append names with a valid extention
    for file in os.listdir(img_dir):
        extension = os.path.splitext(file)[1]
        if extension.lower() not in valid_image_extensions:
            continue
        image_path_list.append(os.path.join(img_dir, file))
    
    return image_path_list
In [98]:
# Create a list with one image for each dog breed. This will allow us to display an image for each 
#  breed predicted in the results.

from glob import glob
import os, random

breed_paths = sorted(glob('dogImages/test/*'))
breed_images = []

for path in breed_paths:
    # randomly select an image
    img_name = random.choice(os.listdir(path))
    breed_images.append('/'.join([path, img_name]))
    
print(breed_images)
['dogImages/test/001.Affenpinscher/Affenpinscher_00058.jpg', 'dogImages/test/002.Afghan_hound/Afghan_hound_00146.jpg', 'dogImages/test/003.Airedale_terrier/Airedale_terrier_00166.jpg', 'dogImages/test/004.Akita/Akita_00282.jpg', 'dogImages/test/005.Alaskan_malamute/Alaskan_malamute_00354.jpg', 'dogImages/test/006.American_eskimo_dog/American_eskimo_dog_00471.jpg', 'dogImages/test/007.American_foxhound/American_foxhound_00484.jpg', 'dogImages/test/008.American_staffordshire_terrier/American_staffordshire_terrier_00556.jpg', 'dogImages/test/009.American_water_spaniel/American_water_spaniel_00631.jpg', 'dogImages/test/010.Anatolian_shepherd_dog/Anatolian_shepherd_dog_00710.jpg', 'dogImages/test/011.Australian_cattle_dog/Australian_cattle_dog_00727.jpg', 'dogImages/test/012.Australian_shepherd/Australian_shepherd_00868.jpg', 'dogImages/test/013.Australian_terrier/Australian_terrier_00925.jpg', 'dogImages/test/014.Basenji/Basenji_00961.jpg', 'dogImages/test/015.Basset_hound/Basset_hound_01044.jpg', 'dogImages/test/016.Beagle/Beagle_01141.jpg', 'dogImages/test/017.Bearded_collie/Bearded_collie_01221.jpg', 'dogImages/test/018.Beauceron/Beauceron_01319.jpg', 'dogImages/test/019.Bedlington_terrier/Bedlington_terrier_01369.jpg', 'dogImages/test/020.Belgian_malinois/Belgian_malinois_01407.jpg', 'dogImages/test/021.Belgian_sheepdog/Belgian_sheepdog_01540.jpg', 'dogImages/test/022.Belgian_tervuren/Belgian_tervuren_01607.jpg', 'dogImages/test/023.Bernese_mountain_dog/Bernese_mountain_dog_01653.jpg', 'dogImages/test/024.Bichon_frise/Bichon_frise_01757.jpg', 'dogImages/test/025.Black_and_tan_coonhound/Black_and_tan_coonhound_01795.jpg', 'dogImages/test/026.Black_russian_terrier/Black_russian_terrier_01837.jpg', 'dogImages/test/027.Bloodhound/Bloodhound_01885.jpg', 'dogImages/test/028.Bluetick_coonhound/Bluetick_coonhound_01968.jpg', 'dogImages/test/029.Border_collie/Border_collie_02056.jpg', 'dogImages/test/030.Border_terrier/Border_terrier_02141.jpg', 'dogImages/test/031.Borzoi/Borzoi_02203.jpg', 'dogImages/test/032.Boston_terrier/Boston_terrier_02297.jpg', 'dogImages/test/033.Bouvier_des_flandres/Bouvier_des_flandres_02339.jpg', 'dogImages/test/034.Boxer/Boxer_02413.jpg', 'dogImages/test/035.Boykin_spaniel/Boykin_spaniel_02497.jpg', 'dogImages/test/036.Briard/Briard_02519.jpg', 'dogImages/test/037.Brittany/Brittany_02601.jpg', 'dogImages/test/038.Brussels_griffon/Brussels_griffon_02707.jpg', 'dogImages/test/039.Bull_terrier/Bull_terrier_02750.jpg', 'dogImages/test/040.Bulldog/Bulldog_02817.jpg', 'dogImages/test/041.Bullmastiff/Bullmastiff_02929.jpg', 'dogImages/test/042.Cairn_terrier/Cairn_terrier_02965.jpg', 'dogImages/test/043.Canaan_dog/Canaan_dog_03066.jpg', 'dogImages/test/044.Cane_corso/Cane_corso_03172.jpg', 'dogImages/test/045.Cardigan_welsh_corgi/Cardigan_welsh_corgi_03185.jpg', 'dogImages/test/046.Cavalier_king_charles_spaniel/Cavalier_king_charles_spaniel_03294.jpg', 'dogImages/test/047.Chesapeake_bay_retriever/Chesapeake_bay_retriever_03395.jpg', 'dogImages/test/048.Chihuahua/Chihuahua_03420.jpg', 'dogImages/test/049.Chinese_crested/Chinese_crested_03489.jpg', 'dogImages/test/050.Chinese_shar-pei/Chinese_shar-pei_03555.jpg', 'dogImages/test/051.Chow_chow/Chow_chow_03637.jpg', 'dogImages/test/052.Clumber_spaniel/Clumber_spaniel_03703.jpg', 'dogImages/test/053.Cocker_spaniel/Cocker_spaniel_03740.jpg', 'dogImages/test/054.Collie/Collie_03849.jpg', 'dogImages/test/055.Curly-coated_retriever/Curly-coated_retriever_03887.jpg', 'dogImages/test/056.Dachshund/Dachshund_03995.jpg', 'dogImages/test/057.Dalmatian/Dalmatian_04021.jpg', 'dogImages/test/058.Dandie_dinmont_terrier/Dandie_dinmont_terrier_04152.jpg', 'dogImages/test/059.Doberman_pinscher/Doberman_pinscher_04190.jpg', 'dogImages/test/060.Dogue_de_bordeaux/Dogue_de_bordeaux_04235.jpg', 'dogImages/test/061.English_cocker_spaniel/English_cocker_spaniel_04359.jpg', 'dogImages/test/062.English_setter/English_setter_04398.jpg', 'dogImages/test/063.English_springer_spaniel/English_springer_spaniel_04440.jpg', 'dogImages/test/064.English_toy_spaniel/English_toy_spaniel_04508.jpg', 'dogImages/test/065.Entlebucher_mountain_dog/Entlebucher_mountain_dog_04595.jpg', 'dogImages/test/066.Field_spaniel/Field_spaniel_04616.jpg', 'dogImages/test/067.Finnish_spitz/Finnish_spitz_04661.jpg', 'dogImages/test/068.Flat-coated_retriever/Flat-coated_retriever_04745.jpg', 'dogImages/test/069.French_bulldog/French_bulldog_04824.jpg', 'dogImages/test/070.German_pinscher/German_pinscher_04875.jpg', 'dogImages/test/071.German_shepherd_dog/German_shepherd_dog_04931.jpg', 'dogImages/test/072.German_shorthaired_pointer/German_shorthaired_pointer_04980.jpg', 'dogImages/test/073.German_wirehaired_pointer/German_wirehaired_pointer_05060.jpg', 'dogImages/test/074.Giant_schnauzer/Giant_schnauzer_05122.jpg', 'dogImages/test/075.Glen_of_imaal_terrier/Glen_of_imaal_terrier_05129.jpg', 'dogImages/test/076.Golden_retriever/Golden_retriever_05221.jpg', 'dogImages/test/077.Gordon_setter/Gordon_setter_05274.jpg', 'dogImages/test/078.Great_dane/Great_dane_05363.jpg', 'dogImages/test/079.Great_pyrenees/Great_pyrenees_05425.jpg', 'dogImages/test/080.Greater_swiss_mountain_dog/Greater_swiss_mountain_dog_05486.jpg', 'dogImages/test/081.Greyhound/Greyhound_05539.jpg', 'dogImages/test/082.Havanese/Havanese_05566.jpg', 'dogImages/test/083.Ibizan_hound/Ibizan_hound_05682.jpg', 'dogImages/test/084.Icelandic_sheepdog/Icelandic_sheepdog_05701.jpg', 'dogImages/test/085.Irish_red_and_white_setter/Irish_red_and_white_setter_05800.jpg', 'dogImages/test/086.Irish_setter/Irish_setter_05819.jpg', 'dogImages/test/087.Irish_terrier/Irish_terrier_05887.jpg', 'dogImages/test/088.Irish_water_spaniel/Irish_water_spaniel_05969.jpg', 'dogImages/test/089.Irish_wolfhound/Irish_wolfhound_06050.jpg', 'dogImages/test/090.Italian_greyhound/Italian_greyhound_06137.jpg', 'dogImages/test/091.Japanese_chin/Japanese_chin_06175.jpg', 'dogImages/test/092.Keeshond/Keeshond_06268.jpg', 'dogImages/test/093.Kerry_blue_terrier/Kerry_blue_terrier_06293.jpg', 'dogImages/test/094.Komondor/Komondor_06378.jpg', 'dogImages/test/095.Kuvasz/Kuvasz_06388.jpg', 'dogImages/test/096.Labrador_retriever/Labrador_retriever_06465.jpg', 'dogImages/test/097.Lakeland_terrier/Lakeland_terrier_06517.jpg', 'dogImages/test/098.Leonberger/Leonberger_06617.jpg', 'dogImages/test/099.Lhasa_apso/Lhasa_apso_06668.jpg', 'dogImages/test/100.Lowchen/Lowchen_06699.jpg', 'dogImages/test/101.Maltese/Maltese_06757.jpg', 'dogImages/test/102.Manchester_terrier/Manchester_terrier_06778.jpg', 'dogImages/test/103.Mastiff/Mastiff_06878.jpg', 'dogImages/test/104.Miniature_schnauzer/Miniature_schnauzer_06916.jpg', 'dogImages/test/105.Neapolitan_mastiff/Neapolitan_mastiff_06937.jpg', 'dogImages/test/106.Newfoundland/Newfoundland_06996.jpg', 'dogImages/test/107.Norfolk_terrier/Norfolk_terrier_07056.jpg', 'dogImages/test/108.Norwegian_buhund/Norwegian_buhund_07124.jpg', 'dogImages/test/109.Norwegian_elkhound/Norwegian_elkhound_07180.jpg', 'dogImages/test/110.Norwegian_lundehund/Norwegian_lundehund_07222.jpg', 'dogImages/test/111.Norwich_terrier/Norwich_terrier_07229.jpg', 'dogImages/test/112.Nova_scotia_duck_tolling_retriever/Nova_scotia_duck_tolling_retriever_07281.jpg', 'dogImages/test/113.Old_english_sheepdog/Old_english_sheepdog_07390.jpg', 'dogImages/test/114.Otterhound/Otterhound_07405.jpg', 'dogImages/test/115.Papillon/Papillon_07514.jpg', 'dogImages/test/116.Parson_russell_terrier/Parson_russell_terrier_07529.jpg', 'dogImages/test/117.Pekingese/Pekingese_07568.jpg', 'dogImages/test/118.Pembroke_welsh_corgi/Pembroke_welsh_corgi_07619.jpg', 'dogImages/test/119.Petit_basset_griffon_vendeen/Petit_basset_griffon_vendeen_07714.jpg', 'dogImages/test/120.Pharaoh_hound/Pharaoh_hound_07750.jpg', 'dogImages/test/121.Plott/Plott_07792.jpg', 'dogImages/test/122.Pointer/Pointer_07812.jpg', 'dogImages/test/123.Pomeranian/Pomeranian_07861.jpg', 'dogImages/test/124.Poodle/Poodle_07949.jpg', 'dogImages/test/125.Portuguese_water_dog/Portuguese_water_dog_07975.jpg', 'dogImages/test/126.Saint_bernard/Saint_bernard_08019.jpg', 'dogImages/test/127.Silky_terrier/Silky_terrier_08055.jpg', 'dogImages/test/128.Smooth_fox_terrier/Smooth_fox_terrier_08110.jpg', 'dogImages/test/129.Tibetan_mastiff/Tibetan_mastiff_08171.jpg', 'dogImages/test/130.Welsh_springer_spaniel/Welsh_springer_spaniel_08190.jpg', 'dogImages/test/131.Wirehaired_pointing_griffon/Wirehaired_pointing_griffon_08245.jpg', 'dogImages/test/132.Xoloitzcuintli/Xoloitzcuintli_08281.jpg', 'dogImages/test/133.Yorkshire_terrier/Yorkshire_terrier_08326.jpg']
In [99]:
# Create sequential list of all dog breed class IDs. This will be our lookup ID when displaying images for predictions.

test_set = load_files('dogImages/test')
class_ids = sorted(set(test_set['target']))
print(class_ids)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132]
In [100]:
# Create a "lookup table" with the breed names and example images

test_image_lookup = list(zip(class_ids, dog_names, breed_images))

test_image_lookup[0:5]
Out[100]:
[(0,
  'Affenpinscher',
  'dogImages/test/001.Affenpinscher/Affenpinscher_00058.jpg'),
 (1, 'Afghan_hound', 'dogImages/test/002.Afghan_hound/Afghan_hound_00146.jpg'),
 (2,
  'Airedale_terrier',
  'dogImages/test/003.Airedale_terrier/Airedale_terrier_00166.jpg'),
 (3, 'Akita', 'dogImages/test/004.Akita/Akita_00282.jpg'),
 (4,
  'Alaskan_malamute',
  'dogImages/test/005.Alaskan_malamute/Alaskan_malamute_00354.jpg')]
In [114]:
### TODO: Write your algorithm.
### Feel free to use as many code cells as needed.

import matplotlib.image as mpimg


def make_prediction(img_path, model):
    _, ax = plt.subplots()
    if dog_detector(img_path):
        print("What's up DOG?!")
        
        # display image
        img = mpimg.imread(img_path)
        _ = ax.imshow(img)
        plt.axis('off')
        plt.show()
        
        # display breeds and confidence scores
        indices, breeds, confidence = Xception_predict_breed(img_path, model)
        predictions = ""
        for i, breed, conf in zip(indices, breeds, confidence):
            predictions += f"\n- {breed} ({conf:.2})"
        print(f"Your breed appears to be:{predictions}")
        
        # display sample of matching breed images
        fig = plt.figure(figsize=(15,4)) 
        for i in enumerate(indices):
            img = mpimg.imread(test_image_lookup[i[1]][2])
            ax = fig.add_subplot(1,3,i[0]+1)
            ax.imshow(img.squeeze(), cmap="gray", interpolation='nearest')
            plt.title(test_image_lookup[i[1]][1])
            plt.axis('off')
        plt.show()
    
    elif face_detector(img_path):
        print("Hey there HUMAN!")
        
        # display image
        img = mpimg.imread(img_path)
        _ = ax.imshow(img)        
        plt.axis('off')
        plt.show()
        
        # display breeds and confidence scores
        indices, breeds, confidence = Xception_predict_breed(img_path, model)
        resemblance = ""
        for i, breed, conf in zip(indices, breeds, confidence):
            resemblance += f"\n- {breed} ({conf:.2})"
        print(f"You resemble these breeds:{resemblance}")
        
        # display sample of matching breed images
        fig = plt.figure(figsize=(15,4)) 
        for i in enumerate(indices):
            img = mpimg.imread(test_image_lookup[i[1]][2])
            ax = fig.add_subplot(1,3,i[0]+1)
            ax.imshow(img.squeeze(), cmap="gray", interpolation='nearest')
            plt.title(test_image_lookup[i[1]][1])
            plt.axis('off')
        plt.show()        
    
    else:
        print("Hmm. I can't determine what you are. ¯\_(ツ)_/¯")
        img = mpimg.imread(img_path)
        _ = ax.imshow(img)        
        plt.axis('off')
        plt.show()
        
    print("\n"*3)

Step 7: Test Your Algorithm

In this section, you will take your new algorithm for a spin! What kind of dog does the algorithm think that you look like? If you have a dog, does it predict your dog's breed accurately? If you have a cat, does it mistakenly think that your cat is a dog?

Test Your Algorithm on Sample Images!

Test your algorithm at least six images on your computer. Feel free to use any images you like. Use at least two human and two dog images.

Question 6: Is the output better than you expected :) ? Or worse :( ? Provide at least three possible points of improvement for your algorithm.

Answer:

The results from running my algorithm on the files in the 'images' directory are excellent. All of the dog breeds appear to be correctly classified, or at least very good guesses.

The output on my custom image set wasn't as accurate, but was still pretty good. This decline in performance could have been hindered by the quality or view angle of my photos. Regardless, here is a summary of the results:

  1. The model recognized all four of the dogs as dogs (100% recall), but misclassified one non-dog as a dog (80% precision).
  2. Of the four dogs, one was classified correctly (the Havanese). Meanwhile, two dogs were incorrectly classified (Poodle mistaken for a Glen of Imaal Terrier, and Old English Sheep Dog mistaken for Petit Basset Griffon Vendeen). One dog was ). The fourth dog is a mutt of unknown origin, so the predictions can't be verified, although they are sensible given the dog's appearance.
  3. There's one interesting case where a statue of a cheetah was mistakenly classified as a Dalmation with 99% confidence. This is interesting because both animals have spots, which seems to indicate that the model can recognize spots (even though it led to an incorrect prediction).
  4. All of the non-human and non-dog picture were correctly classified as unknowns (except for the cheetah).
  5. Some of the human faces were not detected, even when providing a good frontal view.
  6. For many of the human images, the suggested dog breeds do resemble the human in the photo. While there's no objective way to measure this, the predictions often pass the eye test. This is why I setup my algorithm to display example images for the predicted breeds. So that I could see the visually similarities between the input image and the predictions, and at least make a subjective judgement on its accuracy.

Here are some possible improvements:

  1. Incorporate data augmentation to help the model generalize better (e.g. affine transforamtions such as flipping, rotation, cropping, position shifts, color channel shifts, etc). However, this must be done carefully without overly distorting key features of the breed.
  2. Another augmentation approach would be to generate more training examples for the breeds where the error rate is the highest. In other words, re-train the model with the toughest breeds making up a higher percentage of the overall distribution.
  3. Further invest in model tuning to prevent overfitting and get the model to train longer. Right now the model converges in three epochs, which is a low number of training cycles. In the past, the best models I've trained (even when using transfer learning) still needed 10-20 epochs to establish a good set of weights without overfitting. This issue might get resolved by the augmentation steps above. But, if not, I'd experiment further with higher dropout and regularization values.
  4. Display examples of predicted breeds to gain some intuition (and a subjective measure) of how well the predictions fit the input image. (This is now implemented in latest update.)
  5. Ensembling never hurts. Seems like almost every Kaggle winner is applying some sort of ensemble method. :)
In [96]:
## TODO: Execute your algorithm from Step 6 on
## at least 6 images on your computer.
## Feel free to use as many code cells as needed.
In [115]:
# Test algorithm on images provided in '/images' directory. Make predictions for each image. And show an example 
#  for each prediction.

img_dir = 'images'
sample_images = create_img_paths(img_dir)

for img_path in sample_images:
    make_prediction(img_path, Xception_model)
What's up DOG?!
Your breed appears to be:
- Curly-coated_retriever (1.0)
- American_water_spaniel (0.001)
- Irish_water_spaniel (0.00042)



What's up DOG?!
Your breed appears to be:
- American_water_spaniel (0.52)
- Irish_water_spaniel (0.36)
- Curly-coated_retriever (0.08)



What's up DOG?!
Your breed appears to be:
- Labrador_retriever (0.97)
- Chesapeake_bay_retriever (0.03)
- Dogue_de_bordeaux (0.0011)



Hmm. I can't determine what you are. ¯\_(ツ)_/¯



What's up DOG?!
Your breed appears to be:
- Labrador_retriever (0.98)
- Great_dane (0.006)
- Flat-coated_retriever (0.0052)



Hey there HUMAN!
You resemble these breeds:
- Bullmastiff (0.06)
- Chinese_shar-pei (0.038)
- Great_pyrenees (0.027)



Hmm. I can't determine what you are. ¯\_(ツ)_/¯



What's up DOG?!
Your breed appears to be:
- Irish_red_and_white_setter (0.69)
- Welsh_springer_spaniel (0.31)
- Brittany (0.0014)



What's up DOG?!
Your breed appears to be:
- Labrador_retriever (1.0)
- Anatolian_shepherd_dog (0.00056)
- Golden_retriever (0.00013)



What's up DOG?!
Your breed appears to be:
- Brittany (0.97)
- Irish_red_and_white_setter (0.02)
- Nova_scotia_duck_tolling_retriever (0.0056)



In [117]:
# Test algorithm on a custom set of personal images. Make predictions for each image.

img_dir = 'images/test_images'
custom_images = create_img_paths(img_dir)

for img_path in custom_images:
    make_prediction(img_path, Xception_model)
Hey there HUMAN!
You resemble these breeds:
- Glen_of_imaal_terrier (0.16)
- Brittany (0.07)
- Dachshund (0.066)



What's up DOG?!
Your breed appears to be:
- Dalmatian (1.0)
- Chinese_crested (0.00018)
- German_shorthaired_pointer (3.7e-05)



Hey there HUMAN!
You resemble these breeds:
- Dachshund (0.12)
- German_shepherd_dog (0.11)
- Norwich_terrier (0.051)



Hey there HUMAN!
You resemble these breeds:
- Dachshund (0.41)
- English_toy_spaniel (0.057)
- Australian_shepherd (0.055)



Hey there HUMAN!
You resemble these breeds:
- Dachshund (0.084)
- Great_pyrenees (0.08)
- Akita (0.044)



What's up DOG?!
Your breed appears to be:
- Chesapeake_bay_retriever (0.67)
- Dogue_de_bordeaux (0.14)
- Plott (0.099)



Hey there HUMAN!
You resemble these breeds:
- German_shepherd_dog (0.25)
- Dachshund (0.11)
- Glen_of_imaal_terrier (0.048)



What's up DOG?!
Your breed appears to be:
- Havanese (0.56)
- Bichon_frise (0.26)
- Maltese (0.14)



Hmm. I can't determine what you are. ¯\_(ツ)_/¯



Hey there HUMAN!
You resemble these breeds:
- Alaskan_malamute (0.049)
- English_toy_spaniel (0.048)
- Pekingese (0.046)



What's up DOG?!
Your breed appears to be:
- Petit_basset_griffon_vendeen (0.79)
- Old_english_sheepdog (0.15)
- Bearded_collie (0.031)



Hey there HUMAN!
You resemble these breeds:
- German_shepherd_dog (0.27)
- Bull_terrier (0.08)
- Dachshund (0.076)



Hmm. I can't determine what you are. ¯\_(ツ)_/¯



Hmm. I can't determine what you are. ¯\_(ツ)_/¯



Hey there HUMAN!
You resemble these breeds:
- Dachshund (0.12)
- Australian_shepherd (0.11)
- Border_collie (0.05)



What's up DOG?!
Your breed appears to be:
- Glen_of_imaal_terrier (0.38)
- Chinese_crested (0.21)
- Petit_basset_griffon_vendeen (0.07)



Hmm. I can't determine what you are. ¯\_(ツ)_/¯



Hey there HUMAN!
You resemble these breeds:
- Akita (0.16)
- English_toy_spaniel (0.078)
- Glen_of_imaal_terrier (0.044)